package com.quan.bookmall.controller;

import com.quan.bookmall.dto.BookDTO;
import com.quan.bookmall.dto.response.ApiResponse;
import com.quan.bookmall.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class BookController {
    
    private final BookService bookService;
    
    @GetMapping
    public ResponseEntity<?> getAllBooks(
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
        Page<BookDTO> books;
        
        if (name != null && !name.isEmpty()) {
            books = bookService.findByName(name, pageable);
        } else {
            books = bookService.findAll(pageable);
        }
        
        return ResponseEntity.ok(ApiResponse.success(books));
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getBookById(@PathVariable Long id) {
        BookDTO bookDTO = bookService.findById(id);
        return ResponseEntity.ok(ApiResponse.success(bookDTO));
    }
    
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createBook(@Valid @RequestBody BookDTO bookDTO) {
        // 验证ISBN是否已存在
        if (bookService.existsByIsbn(bookDTO.getIsbn())) {
            return ResponseEntity.badRequest().body(ApiResponse.error("ISBN已存在"));
        }
        
        BookDTO createdBook = bookService.create(bookDTO);
        return ResponseEntity.ok(ApiResponse.success(createdBook));
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateBook(
            @PathVariable Long id,
            @Valid @RequestBody BookDTO bookDTO) {
        
        BookDTO updatedBook = bookService.update(id, bookDTO);
        return ResponseEntity.ok(ApiResponse.success(updatedBook));
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteBook(@PathVariable Long id) {
        bookService.delete(id);
        return ResponseEntity.ok(ApiResponse.success("书籍删除成功"));
    }
} 